
from WtfGui import *;
from WtfEngine import *;
from WtfAudio import *;
import copy;

class KeyboardState(CustomGameState):
	def __init__(self):
		CustomGameState.__init__(self);
		
		self.font = Font("v_gui_font");
	
		
		self.seq = ConstantFrequency(0);
		
		opts = WaveGeneratorCreationOptions();
		outOpts = PcmOutputCreationOptions();
		
		self.mux = Multiplexer("Mux", MultiplexerAdditiveType());
		self.generator = PcmOutput("Synth Output", self.mux, outOpts);
		
		
		AudioStream(self.generator).Play(True);
		
		self.AddKey('a', 32.7);
		self.AddKey('w', 34.65);
		self.AddKey('s', 36.71);
		self.AddKey('e', 38.89);
		self.AddKey('d', 41.2);
		self.AddKey('f', 43.65);
		self.AddKey('t', 46.25);
		self.AddKey('g', 49.0);
		self.AddKey('y', 51.91);
		self.AddKey('h', 55.0);
		self.AddKey('u', 58.27);
		self.AddKey('j', 61.74);
		self.AddKey('k', 65.41);
		self.AddKey('l', 2000.00);
		self.AddKey('m', 5.00);
		
		
		
	def AddKey(self, k, freq):
		opts = WaveGeneratorCreationOptions();
		opts.ampFunction = SquareWaveFunction(ConstantFrequency(freq / 4.0));
		gen = WaveGenerator("WaveGen-"+str(k), opts);
		DebugPrint("BitRate = " + str(gen.bitRate));
		
		outOpts = PcmOutputCreationOptions();
		gen = {'stream': AudioStream(PcmOutput("Synth Output", gen, outOpts)),
			'playing': False};
		
		self.BindEvent(
			KeyDownEvent(InputKey(ord(k))), EventHandler(lambda e: self.KeyDown(k, gen))
		);
		self.BindEvent(
			KeyUpEvent(InputKey(ord(k))), EventHandler(lambda e: self.KeyUp(k, gen))
		);
		
	def KeyDown(self, k, gen):
		if not gen['playing']:
			gen['stream'].Play(True);
			gen['playing'] = True;
		#self.mux.AddSource(gen);
		
	def KeyUp(self, k, gen):
		gen['stream'].Stop();
		gen['playing'] = False;
		#self.mux.RemoveSource(gen);
	
def Main(vArg):
	Kernel.GetInst().PushGameState(KeyboardState());
	